import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Create by chenhd on 2021/8/28.
 * 方法四：使用lock condition
 */
public class ConcurrentTask4 {
    public String str;
    public ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        ConcurrentTask4 concurrentTask = new ConcurrentTask4();
        try {
            concurrentTask.lock.lock();
            new Thread(concurrentTask::putStr).start();
            concurrentTask.condition.await();
            System.out.println(concurrentTask.getStr());
        } finally {
            concurrentTask.lock.unlock();
        }
    }

    public void putStr() {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(5);
            this.str = "hello concurrent.";
            condition.signalAll();
        } catch (InterruptedException e) {
            //log error
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public String getStr() {
        return str;
    }
}
